package com.tms.app.tms.ui.home.info;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tms.app.tms.R;
import com.tms.app.tms.adapter.HomeAdapter;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.NotionBean;
import com.tms.app.tms.bean.TaskInfo;
import com.tms.app.tms.bean.response.DTaskRes;
import com.tms.app.tms.codeScan.ScanZxingActivity;
import com.tms.app.tms.db.TaskInfoDBUtil;
import com.tms.app.tms.ui.base.ui.BaseListFragmnet;
import com.tms.app.tms.ui.taskinfo.TaskInfoActivity;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.TimeUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by happy on 2017/8/27.
 */

public class HomeFt extends BaseListFragmnet implements IViewHome, View.OnClickListener {

    @BindView(R.id.toolbar_left)
    TextView toolbarLeft;
    @BindView(R.id.toolbar_center)
    TextView toolbarCenter;
    @BindView(R.id.toolbar_right)
    TextView toolbarRight;
    @BindView(R.id.toolbar_text_right)
    TextView toolbarTextRight;
    @BindView(R.id.toolbar_search_text)
    EditText toolbarSearchText;
    @BindView(R.id.toolbar_search_button)
    Button toolbarSearchButton;
    @BindView(R.id.toolbar_search_parent)
    LinearLayout toolbarSearchParent;
    @BindView(R.id.img_net_error)
    ImageView imgNetError;
    @BindView(R.id.text_net_error)
    TextView textNetError;
    @BindView(R.id.net_errot_layout)
    LinearLayout netErrotLayout;
    @BindView(R.id.text_title_task)
    TextView textTitleTask;
    @BindView(R.id.task_item_parent_no_data)
    LinearLayout taskItemParentNoData;
    @BindView(R.id.text_task_title_bg)
    TextView textTaskTitleBg;
    @BindView(R.id.text_task_status)
    TextView textTaskStatus;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.text_order_no)
    TextView textOrderNo;
    @BindView(R.id.text_fee)
    TextView textFee;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.text_other_fee)
    TextView textOtherFee;
    @BindView(R.id.text_people)
    TextView textPeople;
    @BindView(R.id.text_fabu_title)
    TextView textFabuTitle;
    @BindView(R.id.text_fabu_name)
    TextView textFabuName;
    @BindView(R.id.text_fabu_time)
    TextView textFabuTime;
    @BindView(R.id.text_fabu_type1)
    TextView textFabuType1;
    @BindView(R.id.text_fabu_type2)
    TextView textFabuType2;
    @BindView(R.id.text_fabu_type3)
    TextView textFabuType3;
    @BindView(R.id.task_item_parent)
    LinearLayout taskItemParent;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.img_task_status)
    TextView imgTaskStatus;
    @BindView(R.id.item_progress)
    ProgressBar progress;
    @BindView(R.id.text_read_status)
    TextView textReadStatus;
    @BindView(R.id.layout_waiting_no_data)
    LinearLayout layoutWaitingNoData;
    private HomeP homeP;
    private boolean flag_isTasking = false;
    private LinearLayout task_item_parent;
    private LinearLayout task_item_parent_no_data;
    private int taskingStatus;
    private TaskInfo taskInfo;
    private int REQUEST_CODE_HOME = 0x1234;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        homeP = new HomeP();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.layout_fragment_home, null);
        unbinder = ButterKnife.bind(this, rootView);
        setToolBarTitle(rootView, "卡之佳", 0, R.mipmap.saoyisao);
        setToolBarLisenter(rootView, homeP, this);
        homeP.setiView(this);
        initView(rootView);
        initWatingTask();
        homeP.getData(SharePreferenceUtil.getToken(getContext()));
        return rootView;
    }

    private void initView(View view) {
        adapter = new HomeAdapter(list);
        adapter.setOnItemChildClickListener(homeP);
        adapter.setOnItemClickListener(homeP);
        // GridLayoutManager mgr=new GridLayoutManager(getContext(),3);
        LinearLayoutManager mgr = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mgr);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        task_item_parent = view.findViewById(R.id.task_item_parent);
        task_item_parent_no_data = view.findViewById(R.id.task_item_parent_no_data);
        task_item_parent.setOnClickListener(this);
        swipeLayout.setOnRefreshListener(homeP);
        AnimationDrawable animationDrawable1 = (AnimationDrawable) textTaskTitleBg.getBackground();
        animationDrawable1.start();
        animationDrawable1.setOneShot(false);
    }

    @Override
    public void onStart() {
        super.onStart();
        //  hideLoadingDialog();
        // homeP.getData(SharePreferenceUtil.getToken(getContext()));
//        showLoadingDialog();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            swipeLayout.setRefreshing(false);
        } else {
            if (flag_isTasking) {
                task_item_parent.setVisibility(View.VISIBLE);
                task_item_parent_no_data.setVisibility(View.GONE);
            }
        }
    }


    @Override
    public void handlerErrorMsg(int errorCode) {
        switch (errorCode) {
            case 400://400 无网络 页面
                showNetError();
                break;
            case 401://无网络 弹框
                break;
            case 4100://无任何数据
                showNetError(R.color.white, 4, "您还没有任务\n请您添加任务");
                break;
            case 4101://无执行任务
                break;
            case 4102://无待执行任务
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNotion(NotionBean notionBean) {
        homeP.onRefresh();
        if (!isHidden()) {
            //showLoadingDialog();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskDoing(DTaskRes taskRes) {
        bindTaskdoing(taskRes);
    }

    private void setBusiType(String... busiType) {
        textFabuType1.setVisibility(View.GONE);
        textFabuType2.setVisibility(View.GONE);
        textFabuType3.setVisibility(View.GONE);

        for (String str : busiType) {
            String[] busiTypes = str.split(",");
            for (String type : busiTypes) {
                switch (type) {
                    case "0":
                        textFabuType1.setVisibility(View.VISIBLE);
                        break;
                    case "1":
                        textFabuType2.setVisibility(View.VISIBLE);
                        break;
                    case "2":
                        textFabuType3.setVisibility(View.VISIBLE);
                        break;
                }
            }

        }

    }

    /***
     * 绑定执行中任务
     * @param taskRes
     */
    private void bindTaskdoing(DTaskRes taskRes) {
        if (taskRes.getCode() != 200 || taskRes.getData() == null) {
            task_item_parent_no_data.setVisibility(View.VISIBLE); // 无数据放开
            task_item_parent.setVisibility(View.GONE);
            taskingStatus = 0;
            progress.setProgress(0);
            if (adapter.getData().size() < 1) {
                //showNetError(3);
                return;
            }

        }
        this.taskInfo = taskRes.getData();
        hideNerError();
        textTaskStatus.setText(taskInfo.getDoLineInfo());
        textOrderNo.setText(taskInfo.getAllotPlanNo());
        textFee.setText("￥" + taskInfo.getPrice());
        textTime.setText("做箱时间：" + TimeUtil.getTimeFormat(taskInfo.getDoTime()));
        textPeople.setText("调度人：" + taskInfo.getDispatchUser() + "  " + taskInfo.getDispatchUserPhone());
        textFabuName.setText(taskInfo.getCompanyName());
        textFabuTime.setText(TimeUtil.getTimeFormat(taskInfo.getPublishTime()));
        setBusiType(taskInfo.getBusiType());
        task_item_parent_no_data.setVisibility(View.GONE);// 无数据隐藏
        task_item_parent.setVisibility(View.VISIBLE);
        Glide.with(imgHead.getContext())
                .load(taskInfo.getCompanyImgSrc())
                .error(R.mipmap.default_c)
                .into(imgHead);
        taskingStatus = 1;
        progress.setProgress(taskInfo.getProgress());
        //  imgTaskStatus.getBackground().setLevel(taskInfo.getExecStatus());//0:待执行；1：挂起
        TaskInfoDBUtil.saveOrUpadateTask(taskInfo, 1);
        SharePreferenceUtil.setValue(getContext(), "planId", taskInfo.getAllotPlanId());
    }


    private void initWatingTask() {
        List<TaskInfo> taskInfoList = TaskInfoDBUtil.getTaskList();
        if (taskInfoList != null && taskInfoList.size() > 0) {
            adapter.getData().clear();
            adapter.getData().addAll(taskInfoList);
            adapter.notifyDataSetChanged();
            layoutWaitingNoData.setVisibility(View.GONE);
            hideNerError();
        }else {
            layoutWaitingNoData.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void refreshComplite(String... msg) {
        super.refreshComplite("");
        layoutWaitingNoData.setVisibility(View.GONE);


    }

    @Override
    public void refreshNoData(String... msg) {
        if (taskingStatus == 0) {
            //showNetError(4, "无任务请\n添加任务");
            layoutWaitingNoData.setVisibility(View.VISIBLE);


        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_HOME) {
            try {
                String QRText = data.getStringExtra("QRText");
                showMsg(QRText);
                homeP.checkPlanStatus(SharePreferenceUtil.getToken(getContext()), Integer.parseInt(QRText));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (requestCode == Constant.toTaskInfo) {
            homeP.onRefresh();
            // showLoadingDialog();
        }
    }


    @Override
    @OnClick({R.id.text_net_error, R.id.task_item_parent})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.text_net_error:
                hideNerError();
                break;
            case R.id.task_item_parent:
                intent = new Intent(view.getContext(), TaskInfoActivity.class);
                if (taskInfo == null || taskInfo.getAllotPlanId() < 1) {
                    break;//
                }
                intent.putExtra("planId", taskInfo.getAllotPlanId());
                intent.putExtra("taskType", 2);  //0,没有在执行任务，2，正在执行的任务，1已有在执行任务当前点击为待完成任务
                startActivityForResult(intent, Constant.toTaskInfo);
                break;
            case R.id.toolbar_right_2:
//                 intent=new Intent(view.getContext(), ScanZbarActivity.class);
                intent = new Intent(view.getContext(), ScanZxingActivity.class);
                startActivityForResult(intent, REQUEST_CODE_HOME);
                break;

        }
    }

}
